import { Server } from '../../server'
import { BaseService } from '../BaseService'
import { RedisPool } from './RedisPool'

interface WxAccessTokenConfig {
  accessToken: string,
  expireAt: TimestampSec
}

class RedisKeyBuilder {
  public static USER_TOKEN = 'USER_TOKEN'
  public static WX_ACCESS_TOKEN = 'WX_ACCESS_TOKEN'
  public static WX_SECRET_KEY = 'WX_SECRET_KEY'
}

export class RedisService extends BaseService {

  private pool!: RedisPool

  constructor(server: Server) {
    super(server)
    this.pool = new RedisPool(3)
  }

  public async getWxSecretKey() {
    return this.pool.get(RedisKeyBuilder.WX_SECRET_KEY)
  }

  public async getToken(token: string) {
    return this.pool.hget(RedisKeyBuilder.USER_TOKEN, token)
  }

  public async setAccessToken(info: WxAccessTokenConfig) {
    return this.pool.set(RedisKeyBuilder.WX_ACCESS_TOKEN, JSON.stringify(info))
  }

  public async getAccessToken(): Promise<WxAccessTokenConfig> {
    const res = await this.pool.get(RedisKeyBuilder.WX_ACCESS_TOKEN)
    return JSON.parse(res) || {}
  }
}
